package xdu.lz.stage6_threadpool.chapter2_excutors_threadPoolImpl;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created at 2019/10/23 0023 下午 9:54
 * --
 */
public class CachedThreadPool {


    /**
     * coreSize = 0;
     * MaxSize = Integer.MAX
     * keepAliveTime = 60s
     * blockingQueue = SynchronousQueue
     * threadFactory = Executors.defaultThreadFactory implements ThreadFactory
     * <p>
     * <p>
     * SynchronousQueue特性：
     * SynchronousQueue是一个内部只能包含一个元素的队列。
     * put元素到队列后put方法会被阻塞直到 元素被take。
     * 同样，take元素如果queue为空那么会阻塞直到有元素被put。
     * <p>
     * 只要有任务给newCachedThreadPool就会创建一个线程去跑，跑完后等待1min被回收。
     * 所有都被回收后会自动销毁。
     * 会自动关闭
     * <p>
     * 所以newCachedThreadPool适应于execute many short-lived asynchronous tasks.
     *
     * @return
     */
    private static ExecutorService newCachedThreadPool() {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();

        System.out.println("getActiveCount = " + executor.getActiveCount());

        executor.execute(() -> {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        System.out.println("getActiveCount = " + executor.getActiveCount());

        for (int i = 0; i < 50; i++) {
            executor.execute(() -> {
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            });
        }
        System.out.println("getActiveCount = " + executor.getActiveCount());
        return executor;
    }

    public static void main(String[] args) throws InterruptedException {
        ThreadPoolExecutor service = (ThreadPoolExecutor) newCachedThreadPool();
        int size = -1;
        while (true) {
            if (size != service.getActiveCount()) {
                System.out.println("getActiveCount = " + service.getActiveCount());
                size = service.getActiveCount();
                Thread.sleep(10);
            }
            if (size == 0)
                break;
        }
        System.out.println("所有任务执行完毕，一分钟后被销毁");
    }
}
